package com.carlwang.action;


import java.security.MessageDigest;

import org.apache.commons.lang3.StringUtils;

import com.carlwang.pojo.User;
import com.carlwang.security.BinaryToTextEncoders;
import com.carlwang.service.imp.UserService;
import com.carlwang.util.Constants;
import com.opensymphony.xwork2.ActionSupport;


public class LoginAndRegisterAction extends ActionSupport {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private User mUser;
	private String mAlgorithm = "MD5";
	private int mHashIterations = 1000;
	private String mEncoding = "base16";
	private UserService mUserService;

	public String login() {
		String userName = getUser().getUserName();
		String password = getUser().getPassword();
		validate(userName, password);
		if (hasFieldErrors()) {
			return INPUT;
		}
		encryptPassword(password, userName);
		boolean flag = getUserService().login(getUser());
		if (flag) {
			return INPUT;
		}
		return SUCCESS;
	}

	public String register() {
		String userName = getUser().getUserName();
		String password = getUser().getPassword();
		validate(userName, password);
		if (hasFieldErrors()) {
			return INPUT;
		}
		encryptPassword(password, userName);
		boolean flag = getUserService().create(getUser());
		if (!flag) {
			return INPUT;
		}
		return SUCCESS;
	}

	private void validate(String pUserName, String pPassword) {
		if (StringUtils.isBlank(pUserName)) {
			addFieldError(Constants.USER_NAME, "userName is empty");
		}
		if (StringUtils.isBlank(pPassword)) {
			addFieldError(Constants.PASSWORD, "password is empty");
		}

	}

	
	private void encryptPassword(String pPassword, String pUserName) {
		try {
			MessageDigest md = MessageDigest.getInstance(this.mAlgorithm);
			byte[] data = pPassword.getBytes("UTF-8");
			byte[] salt = pUserName.getBytes("UTF-8");
			if (salt != null) {
				md.update(salt);
			}
			for (int i = 0; i < this.mHashIterations; i++) {
				md.update(data);
				data = md.digest();

			}
			String enctyptPwd = BinaryToTextEncoders.encode(this.mEncoding,
					data);
			getUser().setPassword(enctyptPwd);

		} catch (Exception e) {

		}
	}

	public User getUser() {
		return mUser;
	}

	public void setUser(User user) {
		mUser = user;
	}

	public UserService getUserService() {
		return mUserService;
	}

	public void setUserService(UserService userService) {
		mUserService = userService;
	}

}
